import { Component, Emit, Prop, Watch } from 'vue-facing-decorator'
import Render from '@/render/Render'
import renderModal, {
    getModelValue,
    initModelValue,
    type FormModalDto
} from '@/components/modal/Modal'
import toNative from '@/utils/toNative'
import {
    getKeyToEnum,
    PayModeCnEnum,
    PayModeEnum,
    SaleSceneCnEnum,
    SaleSceneEnum,
    SaleSceneGiftCnEnum,
    SaleSceneGiftEnum
} from '@/const/enum'
import type { OptionDto } from '@/components/low-code/types'
import { confirm, convertCurrency, getReceiptData } from '@/utils/util'
import { createVNode } from 'vue'
import { recharge } from '@/api/pay'
import type { CompanyInfoDto, PayWageInfoDto } from '@/api/company/types'
import { message, Modal } from 'ant-design-vue'
import dayjs from 'dayjs'

@Component
export class DialogRecharge extends Render {
    @Prop({ default: false }) show!: boolean
    @Prop() basicData!: PayWageInfoDto
    @Prop() companyBasicInfo!: CompanyInfoDto

    @Emit('update:show')
    showChange(val: boolean) {
        return val
    }

    @Emit('refresh')
    handleRefresh() {}

    @Watch('show', { immediate: true })
    async handleWatchShow() {
        this.rechargeFormConfig.title = `${this.companyBasicInfo.companyName}子弹发薪充值窗口`
        this.rechargeFormConfig.show = this.show
        // if (this.show) {
        if (this.companyBasicInfo.channelId) {
            this.rechargeFormConfig.items.receiptId.options = await getReceiptData(
                this.companyBasicInfo.channelId
            )
        }
        //     // initModelValue(this.formConfig, this.basicInfo)
        // }
    }

    @Watch('rechargeFormConfig.items.payMoney.value', { deep: true })
    handleWatchPayMoney(newval: number | string) {
        this.rechargeFormConfig.items.hint.params.prefix = newval ? (
            <div class="text-red text-xl">{convertCurrency(newval)}</div>
        ) : (
            <></>
        )
        this.rechargeFormConfig.items.hint.hidden = !newval
    }

    // 充值弹框
    rechargeFormConfig = this.initRechargeFormConfig() as FormModalDto
    initRechargeFormConfig() {
        return {
            title: '',
            width: '600px',
            theme: 'light',
            show: false,
            items: {
                payMode: {
                    name: '付款方式',
                    element: 'select',
                    options: getKeyToEnum(PayModeCnEnum),
                    required: true,
                    callback: {
                        change: (val: number) => {
                            const items = this.rechargeFormConfig.items
                            this.initFormItem()
                            items.salesScenario.value = ''
                            items.salesScenario.options =
                                val === PayModeEnum.GIFT
                                    ? getKeyToEnum(SaleSceneGiftCnEnum)
                                    : getKeyToEnum(SaleSceneCnEnum)
                        }
                    }
                },
                salesScenario: {
                    name: '销售场景',
                    element: 'select',
                    required: true,
                    options: getKeyToEnum(SaleSceneCnEnum),
                    callback: {
                        change: (val: number) => {
                            this.initFormItem()
                        }
                    }
                },
                payMoney: {
                    name: '服务金额',
                    element: 'inputNumber',
                    required: true,
                    defaultValue: 0,
                    params: {
                        min: 0
                    }
                },
                giftAccountTime: {
                    name: '赠送时间',
                    element: 'input',
                    required: true,
                    params: {
                        suffix: '天'
                    },
                    hidden: true,
                    callback: {
                        input: (ev: InputEvent) => {
                            this.setAccountAndSeatExpireTime(ev, 'day')
                        }
                    }
                },
                hint: {
                    name: '',
                    element: 'text',
                    params: {
                        prefix: <></>
                    },
                    hidden: true
                },
                rechargeAmount: {
                    name: '购买月份',
                    element: 'select',
                    required: true,
                    options: this.createMonthOption(),
                    callback: {
                        change: (val: number) => {
                            this.setAccountAndSeatExpireTime(val, 'month')
                        }
                    }
                },
                buySeatCount: {
                    name: '另购席位',
                    element: 'inputNumber',
                    required: true,
                    defaultValue: 1,
                    params: {
                        min: 1
                    },
                    hidden: true
                },
                accountExpireTime: {
                    name: '产品过期时间',
                    element: 'datetime',
                    required: true,
                    labelCol: {
                        style: {
                            width: '8em'
                        }
                    },
                    hidden: true
                },
                seatExpireTime: {
                    name: '席位过期时间',
                    element: 'datetime',
                    labelCol: {
                        style: {
                            width: '8em'
                        }
                    },
                    required: true,
                    hidden: true
                },
                receiptId: {
                    name: '收款账户',
                    element: 'select',
                    optionsType: '',
                    required: true
                },
                voucherUrl: {
                    name: '上传凭证',
                    element: 'upload',
                    type: 'text',
                    params: {
                        autoUpload: false,
                        accept: '.png,.jpg,.jpeg',
                        suffix: (
                            <div class="text-sm text-gray">
                                大小限制5MB，支持png、jpeg、jpg格式文件
                            </div>
                        )
                    }
                },
                remark: {
                    name: '备注',
                    element: 'textarea',
                    params: { rows: 4 }
                }
            },
            complete: async () => {
                const data = getModelValue(this.rechargeFormConfig)

                const res = await confirm(
                    createVNode('span', null, [
                        '充值动作不可逆，本次充值',
                        createVNode(
                            'strong',
                            {
                                style: {
                                    color: 'red'
                                }
                            },
                            data.payMoney
                        ),
                        '元，确认充值？'
                    ])
                )

                delete data.hint
                delete data.giftAccountTime
                data.companyId = this.basicData.companyId
                data.openAccountMoney = 0

                if (data.voucherUrl?.length && Array.isArray(data.voucherUrl)) {
                    const base64 = data.voucherUrl[0].base64
                    data.voucherUrl = base64.split(';base64,')[1]
                }

                await recharge(data)
                message.success('更新成功')
                this.rechargeFormConfig.show = false
                this.showChange(false)
                this.handleRefresh()
            },
            cancel: () => {
                this.rechargeFormConfig.show = false
                this.showChange(false)
            },
            init: () => {
                initModelValue(this.rechargeFormConfig)
            }
        } as FormModalDto
    }

    createMonthOption() {
        const arr = [] as OptionDto[]
        for (let i = 1; i <= 12; i++) {
            arr.push({ label: `${i}月`, value: i })
        }
        return arr
    }

    initFormItem() {
        const formData = getModelValue(this.rechargeFormConfig)
        const items = this.rechargeFormConfig.items

        const hasSeat =
            formData.salesScenario === SaleSceneGiftEnum.PRODUCT_AND_SEAT ||
            formData.salesScenario === SaleSceneGiftEnum.SEAT ||
            formData.salesScenario === SaleSceneEnum.EXTEND_AND_SEAT ||
            formData.salesScenario === SaleSceneEnum.FITST_AND_SEAT ||
            formData.salesScenario === SaleSceneEnum.SEAT
        const hasProcuct =
            formData.salesScenario === SaleSceneGiftEnum.PRODUCT_AND_SEAT ||
            formData.salesScenario === SaleSceneGiftEnum.PRODUCT ||
            formData.salesScenario === SaleSceneEnum.FIRST_SIGN ||
            formData.salesScenario === SaleSceneEnum.EXTEND_SIGN ||
            formData.salesScenario === SaleSceneGiftEnum.PRODUCT ||
            formData.salesScenario === SaleSceneEnum.FITST_AND_SEAT ||
            formData.salesScenario === SaleSceneEnum.EXTEND_AND_SEAT

        items.giftAccountTime.hidden = formData.payMode !== PayModeEnum.GIFT

        items.payMoney.hidden = formData.payMode === PayModeEnum.GIFT
        items.rechargeAmount.hidden = formData.payMode === PayModeEnum.GIFT
        items.voucherUrl.hidden = formData.payMode === PayModeEnum.GIFT

        items.buySeatCount.name = formData.payMode === PayModeEnum.GIFT ? '赠送席位' : '另购席位'
        items.buySeatCount.hidden = !hasSeat
        items.accountExpireTime.hidden = !hasProcuct
        items.seatExpireTime.hidden = !hasSeat
    }

    setAccountAndSeatExpireTime(month: number | InputEvent, type: 'month' | 'day') {
        const expireTime = this.basicData.accountExpireTime
            ? new Date(this.basicData.accountExpireTime).getTime()
            : 0
        const nowTime = new Date().getTime()
        const formData = getModelValue(this.rechargeFormConfig)
        const setDate = expireTime > nowTime ? this.basicData.accountExpireTime : new Date()

        formData.accountExpireTime = dayjs(setDate)
            .add(month as number, type)
            .toISOString()
        formData.seatExpireTime = dayjs(new Date())
            .add(month as number, type)
            .toISOString()
        initModelValue(this.rechargeFormConfig, formData)
    }

    render() {
        return <div>{renderModal(this.rechargeFormConfig)}</div>
    }
}

export default toNative<
    { basicData: PayWageInfoDto; companyBasicInfo: CompanyInfoDto },
    { refresh: () => void }
        >(DialogRecharge)
